/*
 * @Author: LiJia
 * @Date: 2021-03-01 16:59:33
 * @LastEditTime: 2021-04-03 14:14:15
 * @LastEditors: LiJia
 * @Description: Description
 * @FilePath: \class-manage-system\miniprogram\pages\index\index.ts
 */
// index.ts
// 获取应用实例
const app = getApp<IAppOption>()

Page({
  data: {
    motto: '欢迎使用课程管理系统！',
    userInfo: {},
    clsUserInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
  },
  /**
   * 页面初始化函数
   */ 
  onLoad() {
    wx.showToast({
      title: '加载中用户数据中...',
      icon: 'loading',
      duration: 1800
    })
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },

  /**
   * 获取用户信息 新
   */
  getUserProfile(e: any) {
    console.log(e)
    wx.getUserProfile({
      desc: '信息获取中...', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res: any) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        app.globalData.userInfo = res.userInfo
        app.globalData.clsUserInfo = { ...app.globalData.clsUserInfo, ...app.globalData.userInfo }
      },
      fail: (err: any) => {
        console.log(err)
      }
    })
  },

  /**
   * 跳转到主页面 
   * 1. 传递参数 classUserInfo
   */
  toMainMenu() {
    this.getClsUserInfo()
    let that = this
    setTimeout(() => {
      wx.navigateTo({
        // url: '/pages/mine/children/my-test/my-test',
        // url: '/pages/mine/children/my-homework/my-homework',
        url: '/pages/main/main',
        // url: '../mine/main/mine',
        // url: '/pages/mine/children/signin/signin',
        success: (res) => {
          // 通过eventChannel向被打开页面传送数据
          res.eventChannel.emit('clsUserInfo', { data: that.data.clsUserInfo })
        }
      })
    }, 500)
  },

  /**
   * 获取管理系统用户信息
   * param: userInfo
   */
  getClsUserInfo() {
    this.setData({
      clsUserInfo: { ...app.globalData.clsUserInfo, ...app.globalData.userInfo }
    })
  },

  getUserInfo(e: any) {
    // console.log(e)
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        motto: "你好，" + e.detail.userInfo.nickName + "！",
        userInfo: e.detail.userInfo,
        hasUserInfo: true,
      })
      console.log(this.data.motto)
    } else {
      wx.showToast({
        title: '您拒绝了小程序授权！',
        icon: 'none',
        duration: 1500
      })
    }
  },
})
